from PyQt6.QtWidgets import (QWidget, QVBoxLayout, QHBoxLayout, QLabel,
                             QProgressBar, QPushButton, QRadioButton,
                             QCheckBox, QButtonGroup, QScrollArea, QApplication,
                             QGridLayout)
from PyQt6.QtCore import QTimer, Qt
from PyQt6.QtGui import QFont
from qfluentwidgets import (CardWidget, PushButton, PrimaryPushButton,
                            TitleLabel, BodyLabel, StrongBodyLabel,
                            InfoBar, InfoBarPosition, LineEdit)
from dbutil.db_handler import DatabaseHandler
import json

class ExamPaperWindow(QWidget):
    def __init__(self, username, paper_id):
        super().__init__()
        self.username = username
        self.paper_id = paper_id
        self.current_question = 0
        self.total_questions = 0
        self.questions = []
        self.marked_questions = set()
        self.answered_questions = set()  # 新增：记录已回答的题目
        self.setup_ui()
        self.load_questions()
        self.start_timer()

    def setup_ui(self):
        self.setWindowTitle(f"试卷 {self.paper_id} - 习题练习")
        self.resize(1200, 800)
        self.setStyleSheet("""
            QWidget {
                background: #f5f5f5;
            }
        """)

        # 主布局
        main_layout = QHBoxLayout(self)
        main_layout.setContentsMargins(20, 20, 20, 20)
        main_layout.setSpacing(10)

        # 左侧题卡
        left_panel = CardWidget()
        left_panel.setFixedWidth(300)
        left_layout = QVBoxLayout(left_panel)
        left_layout.setContentsMargins(15, 15, 15, 15)
        left_layout.setSpacing(15)

        # 用户名
        user_label = TitleLabel(f"用户: {self.username}")
        user_label.setStyleSheet("font-size: 18px; color: #0078d4;")
        left_layout.addWidget(user_label)

        # 倒计时
        self.timer_label = StrongBodyLabel("剩余时间: 60:00")
        self.timer_label.setStyleSheet("font-size: 16px; color: #d13438;")
        left_layout.addWidget(self.timer_label)

        # 交卷按钮
        self.submit_btn = PrimaryPushButton("交卷")
        self.submit_btn.clicked.connect(self.submit_exam)
        left_layout.addWidget(self.submit_btn)

        # 进度条
        self.progress_bar = QProgressBar()
        self.progress_bar.setRange(0, 100)
        self.progress_bar.setValue(0)
        self.progress_bar.setStyleSheet("""
            QProgressBar {
                height: 20px;
                border-radius: 10px;
                background: #e1e1e1;
            }
            QProgressBar::chunk {
                background: #0078d4;
                border-radius: 10px;
            }
        """)
        left_layout.addWidget(self.progress_bar)

        # 题目分类容器
        self.question_containers = {
            '单选题': {'layout': QVBoxLayout(), 'buttons': [], 'count': 25},
            '多选题': {'layout': QVBoxLayout(), 'buttons': [], 'count': 15},
            '判断题': {'layout': QVBoxLayout(), 'buttons': [], 'count': 10},
            '填空题': {'layout': QVBoxLayout(), 'buttons': [], 'count': 5}
        }

        # 添加分类标题和容器
        for q_type, container in self.question_containers.items():
            group_box = CardWidget()
            group_layout = QVBoxLayout(group_box)
            group_layout.setContentsMargins(10, 10, 10, 10)
            group_layout.setSpacing(8)
            
            title = TitleLabel(f"{q_type} ({container['count']}题)")
            title.setStyleSheet("font-size: 16px; font-weight: bold;")
            group_layout.addWidget(title)
            
            # 添加题号按钮容器
            button_container = QWidget()
            button_layout = QGridLayout(button_container)
            button_layout.setSpacing(4)
            button_layout.setContentsMargins(2, 2, 2, 2)
            
            group_layout.addWidget(button_container)
            container['button_container'] = button_container
            container['button_layout'] = button_layout
            group_layout.addLayout(container['layout'])
            left_layout.addWidget(group_box)

        # 右侧答题区域
        right_panel = CardWidget()
        # right_panel.setFixedHeight(400)
        right_panel.setContentsMargins(0, 0, 0, 300)
        right_layout = QVBoxLayout(right_panel)
        right_layout.setContentsMargins(15, 8, 15, 8)  # 进一步减少上下边距
        right_layout.setSpacing(20)  # 进一步减少组件间距


        # 题目显示区域
        self.question_label = BodyLabel()
        self.question_label.setStyleSheet("""
            font-size: 18px; 
            color: #333; 
            line-height: 1.4;
            margin: 2px 0;  # 减少上下边距
        """)
        self.question_label.setWordWrap(True)
        right_layout.addWidget(self.question_label)

        # 选项容器
        self.options_group = QButtonGroup()
        self.options_layout = QVBoxLayout()
        self.options_layout.setSpacing(5)  # 进一步减少选项间距
        self.options_layout.setContentsMargins(3, 3, 3, 3)  # 减少内边距
        right_layout.addLayout(self.options_layout)

        # 底部按钮
        bottom_layout = QHBoxLayout()
        bottom_layout.setSpacing(6)  # 进一步减少按钮间距
        self.prev_btn = PushButton("上一题")
        self.prev_btn.setFixedWidth(90)  # 减少按钮宽度
        self.prev_btn.clicked.connect(self.prev_question)
        self.mark_btn = PushButton("标记")
        self.mark_btn.setFixedWidth(90)  # 减少按钮宽度
        self.mark_btn.clicked.connect(self.toggle_mark)
        self.next_btn = PushButton("下一题")
        self.next_btn.setFixedWidth(90)  # 减少按钮宽度
        self.next_btn.clicked.connect(self.next_question)
        bottom_layout.addWidget(self.prev_btn)
        bottom_layout.addWidget(self.mark_btn)
        bottom_layout.addWidget(self.next_btn)
        bottom_layout.setContentsMargins(0, 100, 0, 50)
        right_layout.addLayout(bottom_layout)

        # 设置主布局
        main_layout.addWidget(left_panel)
        main_layout.addWidget(right_panel)

    def load_questions(self):
        db = DatabaseHandler()
        query = f"SELECT * FROM questions WHERE paper_id = {self.paper_id}"
        if db.connect():
            self.questions = db.execute_query(query)
            db.disconnect()
        
        self.total_questions = len(self.questions)
        if self.total_questions > 0:
            self.update_question_numbers()
            self.load_question(0)
            self.update_progress()

    def update_question_numbers(self):
        """更新所有题号按钮"""
        # 清空现有按钮
        for container in self.question_containers.values():
            for btn in container['buttons']:
                btn.setParent(None)
            container['buttons'].clear()

        # 按题目类型分组
        question_groups = {
            '单选题': [],
            '多选题': [],
            '判断题': [],
            '填空题': []
        }
        for i, question in enumerate(self.questions):
            question_groups[question['question_type']].append(i)

        # 为每种题型添加题号按钮
        for q_type, indices in question_groups.items():
            container = self.question_containers[q_type]
            button_layout = container['button_layout']
            buttons_per_row = 5  # 每行显示5个按钮

            for idx, question_idx in enumerate(indices):
                row = idx // buttons_per_row
                col = idx % buttons_per_row
                btn = PushButton(f"{question_idx + 1}")
                btn.setFixedSize(36, 36)
                btn.setStyleSheet(f"""
                    QPushButton {{
                        font-size: 12px;
                        border-radius: 18px;
                        background: {self.get_button_color(question_idx)};
                        color: white;
                    }}
                    QPushButton:hover {{
                        background: {self.get_button_hover_color(question_idx)};
                    }}
                """)
                btn.clicked.connect(lambda _, num=question_idx: self.load_question(num))
                button_layout.addWidget(btn, row, col)
                container['buttons'].append(btn)

    def get_button_color(self, index):
        """动态获取按钮颜色"""
        if index == self.current_question:
            return "#ffc107"  # 当前题目
        if index in self.marked_questions:
            return "#dc3545"  # 已标记题目
        if index in self.answered_questions:
            return "#90EE90"  # 已回答的题目，浅绿色
        return "#007BFF"     # 普通状态

    def get_button_hover_color(self, index):
        """动态获取按钮悬停颜色"""
        if index == self.current_question:
            return "#ffca2c"
        if index in self.marked_questions:
            return "#bb2d3b"
        if index in self.answered_questions:
            return "#7CFC00"  # 已回答的题目，悬停时更亮的绿色
        return "#0056b3"

    def load_question(self, question_num):
        if question_num < 0 or question_num >= self.total_questions:
            return

        self.current_question = question_num
        question_data = self.questions[question_num]

        # 更新所有题号按钮状态
        self.update_question_numbers()

        # 清空选项
        for i in reversed(range(self.options_layout.count())):
            widget = self.options_layout.itemAt(i).widget()
            if widget:
                widget.setParent(None)

        # 显示题目
        self.question_label.setText(question_data['question_text'])

        # 显示选项
        options = question_data['options']
        if options:
            try:
                options = json.loads(options)
            except json.JSONDecodeError as e:
                print(f"JSON decode error: {e}")
                options = None
        else:
            print("Options is None or empty")
            options = None

        if question_data['question_type'] in ['单选题', '多选题']:
            for option in options:
                if question_data['question_type'] == '单选题':
                    btn = QRadioButton(option)
                    btn.setStyleSheet("""
                        QRadioButton {
                            font-size: 18px;
                            spacing: 8px;
                            padding: 6px;
                        }
                    """)
                    btn.toggled.connect(self.update_answer_status)
                else:
                    btn = QCheckBox(option)
                    btn.setStyleSheet("""
                        QCheckBox {
                            font-size: 18px;
                            spacing: 8px;
                            padding: 6px;
                        }
                    """)
                    btn.stateChanged.connect(self.update_answer_status)
                self.options_layout.addWidget(btn)
        elif question_data['question_type'] == '判断题':
            true_btn = QRadioButton("正确")
            true_btn.setStyleSheet("""
                QRadioButton {
                    font-size: 18px;
                    spacing: 8px;
                    padding: 6px;
                }
            """)
            true_btn.toggled.connect(self.update_answer_status)
            false_btn = QRadioButton("错误")
            false_btn.setStyleSheet("""
                QRadioButton {
                    font-size: 18px;
                    spacing: 8px;
                    padding: 6px;
                }
            """)
            false_btn.toggled.connect(self.update_answer_status)
            self.options_layout.addWidget(true_btn)
            self.options_layout.addWidget(false_btn)
        elif question_data['question_type'] == '填空题':
            self.answer_input = LineEdit()
            self.answer_input.setPlaceholderText("请输入答案")
            self.answer_input.setStyleSheet("""
                QLineEdit {
                    font-size: 18px;
                    padding: 6px;
                }
            """)
            self.answer_input.textChanged.connect(self.update_answer_status)
            self.options_layout.addWidget(self.answer_input)

        # 更新按钮状态
        self.update_navigation_buttons()

    def update_answer_status(self):
        """更新答题状态"""
        self.answered_questions.add(self.current_question)
        self.update_question_numbers()
        self.update_progress()

    def update_navigation_buttons(self):
        self.prev_btn.setEnabled(self.current_question > 0)
        self.next_btn.setEnabled(self.current_question < self.total_questions - 1)
        self.mark_btn.setText("取消标记" if self.current_question in self.marked_questions else "标记")

    def toggle_mark(self):
        if self.current_question in self.marked_questions:
            self.marked_questions.remove(self.current_question)
        else:
            self.marked_questions.add(self.current_question)
        self.update_navigation_buttons()

    def prev_question(self):
        if self.current_question > 0:
            self.load_question(self.current_question - 1)

    def next_question(self):
        if self.current_question < self.total_questions - 1:
            self.load_question(self.current_question + 1)

    def start_timer(self):
        self.remaining_time = 60 * 60  # 60分钟
        self.timer = QTimer()
        self.timer.timeout.connect(self.update_timer)
        self.timer.start(1000)  # 每秒更新一次

    def update_timer(self):
        self.remaining_time -= 1
        minutes = self.remaining_time // 60
        seconds = self.remaining_time % 60
        self.timer_label.setText(f"剩余时间: {minutes:02d}:{seconds:02d}")

        if self.remaining_time <= 0:
            self.timer.stop()
            self.submit_exam()

    def update_progress(self):
        """更新进度条"""
        progress = int(len(self.answered_questions) / self.total_questions * 100)
        self.progress_bar.setValue(progress)
        self.progress_bar.setFormat(f"已完成 {len(self.answered_questions)}/{self.total_questions} 题")

    def submit_exam(self):
        InfoBar.success(
            title="交卷成功",
            content="您的试卷已成功提交！",
            orient=Qt.Orientation.Horizontal,
            isClosable=True,
            position=InfoBarPosition.TOP,
            duration=2000,
            parent=self
        )
        self.close()

if __name__ == "__main__":
    app = QApplication([])
    window = ExamPaperWindow("test_user", 1)
    window.show()
    app.exec() 